#!/usr/bin/env perl

=pod

This is a Nagios (http://www.nagios.org/) check script to see that the
"last_replication_date" of a mirror (RT_MIRROR) MusicBrainz server is not too
old.

=cut

use FindBin;
use lib "$FindBin::Bin/../../lib";

use strict;
use DBDefs;
use MusicBrainz::Server::Context;
use Sql;
use integer;

use Getopt::Long;

my $warn = 3600 * 6;
my $crit = 3600 * 24;

GetOptions(
    'warn|w=i'  => \$warn,
    'critical|c=i'      => \$crit,
) or exit 2;

@ARGV == 0 or die "Usage: $0 [-w SECONDS] [-c SECONDS]\n";

if (DBDefs->REPLICATION_TYPE != DBDefs::RT_MIRROR)
{
    print "This is not a mirror database!\n";
    exit 2;
}

my $c = MusicBrainz::Server::Context->create_script_context;

my $row = $c->sql->select_single_row_hash(
    '
    SELECT
    (last_replication_date < NOW() - ?::INTERVAL) as warn,
    (last_replication_date < NOW() - ?::INTERVAL) as crit,
    last_replication_date,
    NOW() - last_replication_date as age
    FROM replication_control
    ',
    "$warn seconds",
    "$crit seconds",
);

if (not $row)
{
    print "No replication control data!\n";
    exit 2;
}

print ($row->{crit} ? 'CRITICAL' : $row->{warn} ? 'WARNING' : 'OK');
print ': ';
print "Last replication date is $row->{last_replication_date} (age = $row->{age})\n";
exit ($row->{crit} ? 2 : $row->{warn} ? 1 : 0);

=head1 COPYRIGHT AND LICENSE

Copyright (C) 1998 Robert Kaye

This file is part of MusicBrainz, the open internet music database,
and is licensed under the GPL version 2, or (at your option) any
later version: http://www.gnu.org/licenses/gpl-2.0.txt

=cut
